package com.sanjiahantang.youjiarole.module.apk.views.impl;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.StaticValue;
import com.sanjiahantang.youjiarole.module.apk.ApkDownloadUtils;
import com.sanjiahantang.youjiarole.utils.FileUtils;
import com.sanjiahantang.youjiarole.utils.SDCardUtils;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * Created by yan on 2017/12/11.
 */

public class ProgressActivity extends AppCompatActivity {

    private ProgressBar progress_layout_progressbar;

    private TextView progress_layout_speed_tv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setFinishOnTouchOutside(false);

        initView();
        initData();
    }

    private void initView() {
        setContentView(R.layout.progress_layout);
        progress_layout_progressbar = (ProgressBar) this.findViewById(R.id.progress_layout_progressbar);
        progress_layout_speed_tv = (TextView) this.findViewById(R.id.progress_layout_speed_tv);
    }

    private void initData() {
        String url = this.getIntent().getStringExtra(StaticValue.KEY_OBJECT);
        if (isGrantExternalRW()) {
            if (!url.isEmpty() && SDCardUtils.isSDCardEnable()) {
                createDownloadTask(FileUtils.rePath(url)).start();
            }
        }
    }

    /**
     * 读写权限
     *
     * @return
     */
    private boolean isGrantExternalRW() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && this.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);

            return false;
        }

        return true;
    }

    private BaseDownloadTask createDownloadTask(String url) {
        boolean isDir = false;
        String path;

        ViewHolder tag = new ViewHolder(new WeakReference<>(this), progress_layout_progressbar, progress_layout_speed_tv);
        if (SDCardUtils.isSDCardEnable()) {

            path = SDCardUtils.getAPKPath(ProgressActivity.this);
        } else {
            path = "";
        }


        return FileDownloader.getImpl().create(url)
                .setPath(path, isDir)
                .setCallbackProgressTimes(300)
                .setMinIntervalUpdateSpeed(400)
                .setTag(tag)
                .setListener(listener);
    }

    private FileDownloadSampleListener listener = new FileDownloadSampleListener() {

        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            super.pending(task, soFarBytes, totalBytes);
            ((ViewHolder) task.getTag()).updatePending(task);
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            super.progress(task, soFarBytes, totalBytes);
            ((ViewHolder) task.getTag()).updateProgress(soFarBytes, totalBytes,
                    task.getSpeed());
        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            super.error(task, e);
            ((ViewHolder) task.getTag()).updateError(e, task.getSpeed());
            finish();
        }

        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
            super.connected(task, etag, isContinue, soFarBytes, totalBytes);
            ((ViewHolder) task.getTag()).updateConnected(etag, task.getFilename());
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            super.paused(task, soFarBytes, totalBytes);
            ((ViewHolder) task.getTag()).updatePaused(task.getSpeed());
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            super.completed(task);
            ((ViewHolder) task.getTag()).updateCompleted(task);

            ApkDownloadUtils.openFile(task.getPath(), ProgressActivity.this);
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            super.warn(task);
            ((ViewHolder) task.getTag()).updateWarn();
        }
    };

    /**
     *
     */
    private static class ViewHolder {
        private ProgressBar pb;
        private TextView speedTv;

        private WeakReference<ProgressActivity> weakReferenceContext;

        public ViewHolder(WeakReference<ProgressActivity> weakReferenceContext,
                          final ProgressBar pb, final TextView speedTv
        ) {
            this.weakReferenceContext = weakReferenceContext;
            this.pb = pb;
            this.speedTv = speedTv;
        }


        private void updateSpeed(int speed) {
            speedTv.setText("下载进度 " + String.format("%dKB/s", speed));
        }

        public void updateProgress(final int sofar, final int total, final int speed) {
            if (total == -1) {
                // chunked transfer encoding data
                pb.setIndeterminate(true);
            } else {
                pb.setMax(total);
                pb.setProgress(sofar);
            }

            updateSpeed(speed);


        }

        public void updatePending(BaseDownloadTask task) {

        }

        public void updatePaused(final int speed) {
            updateSpeed(speed);
            pb.setIndeterminate(false);
        }

        public void updateConnected(String etag, String filename) {

        }

        public void updateWarn() {
            pb.setIndeterminate(false);
        }

        public void updateError(final Throwable ex, final int speed) {
            updateSpeed(speed);
            pb.setIndeterminate(false);
            ex.printStackTrace();
        }

        public void updateCompleted(final BaseDownloadTask task) {


            updateSpeed(task.getSpeed());
            pb.setIndeterminate(false);
            pb.setMax(task.getSmallFileTotalBytes());
            pb.setProgress(task.getSmallFileSoFarBytes());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileDownloader.getImpl().pause(listener);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
